<template>
  <el-dialog
      v-model="JfwbDialogcompile"
      title="经费外拨编辑"
      :close-on-click-modal="false"
      width="80%"
  >
    <div  v-loading="loading" >
      <div>
        <div class="title-col">基本信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">
            <el-input disabled v-model="projectInfo.projectName" placeholder="请输入支出科目" />
          </el-descriptions-item>
          <el-descriptions-item label="负责人">
            {{ projectInfo.chargerName }}
          </el-descriptions-item>
          <el-descriptions-item label="外拨总金额(万元)">
            {{ turnWanyuan(projectInfo.outFee) }}
          </el-descriptions-item>
          <el-descriptions-item label="已拨经费(万元)">
            {{ turnWanyuan(projectInfo.isOutFee) }}
          </el-descriptions-item>
          <el-descriptions-item label="可外拨金额(万元)">
            {{ turnWanyuan(projectInfo.notOutFee )}}
          </el-descriptions-item>

          <el-descriptions-item label="申请外拨日期">
            <el-date-picker
                v-model="projectInfo.outbounddate"
                type="date"
                placeholder="选择申请外拨日期"
                @change="handleDateChange"
            />
          </el-descriptions-item>
          <el-descriptions-item label="外拨待审核金额(万元)">
            {{ turnWanyuan(projectInfo.outFeeIncheck) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div>
        <div class="title-col">外拨信息</div>
        <el-table :data="projectInfo.projectOutboundList" border>
          <el-table-column label="序号" width="80">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="合作单位名称"></el-table-column>
          <el-table-column prop="chargerName" label="负责人"></el-table-column>
          <el-table-column prop="status" label="已外拨/未外拨(万元)">
            <template #default="scope">
              {{ turnWanyuan(scope.row.isOutFee)}}/{{turnWanyuan(scope.row.notOutFee)}}
            </template>
          </el-table-column>
          <el-table-column label="外拨经费(万元)">
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.outboundFee"
                  :min="0"
                  @blur="handleOutboundFeeBlur(scope.row)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="银行名称">
            <template #default="scope">
              <el-input v-model="scope.row.bankName" placeholder="请输入银行名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="银行账号">
            <template #default="scope">
              <el-input v-model="scope.row.bankNum" placeholder="请输入银行账号"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">

        <div>
          <!-- 科研人员 -->
          <el-button v-if="verifyRoleType.isKyry()" type="primary" @click="handleSave">暂存</el-button>
          <el-button v-if="verifyRoleType.isKyry()" type="primary" @click="submit">提交</el-button>
          <el-button v-if="verifyRoleType.isKyry()" type="primary" @click="JfwbDialogcompile = false">关闭</el-button>

          <!-- 科研秘书 -->
          <template v-if="verifyRoleType.isKyms()">
            <!-- 暂存状态 -->
            <el-button v-if="projectInfo.checkstatus == -1" type="primary" @click="handleSave">暂存</el-button>
            <el-button v-if="projectInfo.checkstatus == -1" type="primary" @click="JfwbDialogcompile = false">关闭</el-button>
            <!-- 审批中状态 -->
            <el-button v-if="projectInfo.checkstatus == 1" type="primary" @click="handleSave">暂存</el-button>
            <el-button v-if="projectInfo.checkstatus == 1 && projectInfo.isAuditor === true" type="primary" @click="handleSaveAndPass">保存并通过</el-button>
            <el-button v-if="projectInfo.checkstatus == 1" type="primary" @click="JfwbDialogcompile = false">关闭</el-button>
          </template>

          <!-- 科研管理员 -->
          <template v-if="verifyRoleType.iskycgly()">
            <!-- 暂存状态 -->
            <el-button v-if="projectInfo.checkstatus == -1" type="primary" @click="handleSave">暂存</el-button>
            <el-button v-if="projectInfo.checkstatus == -1 && projectInfo.isAuditor === true" type="primary" @click="handleSaveAndPass">保存并通过</el-button>
            <el-button v-if="projectInfo.checkstatus == -1" type="primary" @click="JfwbDialogcompile = false">关闭</el-button>
            <!-- 审批中状态 -->
            <el-button v-if="projectInfo.checkstatus == 1" type="primary" @click="handleSave">暂存</el-button>
            <el-button v-if="projectInfo.checkstatus == 1 && projectInfo.isAuditor === true" type="primary" @click="handleSaveAndPass">保存并通过</el-button>
            <el-button v-if="projectInfo.checkstatus == 1" type="primary" @click="JfwbDialogcompile = false">关闭</el-button>
          </template>
        </div>


        <!--        <el-button @click="handleSave">暂存</el-button>-->
        <!--        <el-button @click="submit" v-if="verifyRoleType.isKyry()">提交</el-button>-->
        <!--        <el-button v-if="verifyRoleType.isKymsOrkycgly() && projectInfo.isAuditor === true" type="primary" @click="handleSaveAndPass">保存并通过</el-button>-->
        <!--        <el-button @click="JfwbDialogcompile = false">关闭</el-button>-->
      </div>
    </template>

  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits } from "vue";
import {
  getEditInfo,
  edit
} from '@/api/money/jfwbApi.js'
import {turnWanyuan, turnyuan, convertOutboundFeeToYuan, convertOutboundFeeToWanYuan} from './../../../utils/money.js'
import { ElMessage } from "element-plus";
import { verifyRoleType } from "@/utils/main";
const loading = ref(false) // 添加加载状态


// //获取登录中文name
// import useUserStore from "@/store/modules/user";
// const userStore = useUserStore();
// alert(userStore.nickName)
// //获取登录name
// 接收父组件传递的 props
const props = defineProps({
  projectInfo: {
    type: Object,
    default: () => ({})
  },
  tableData: {
    type: Array,
    default: () => []
  }
});

// 模拟表格数据
const tableData = ref([
  {
    index: 3600,
    coopUnitName: '合作单位 1',
    leader: '李四',
    status: '未外拨',
    isOutFee: 0,
    bankName: '',
    bankAccount: ''
  },
  {
    index: 2,
    coopUnitName: '合作单位 2',
    leader: '王五',
    status: '已外拨',
    isOutFee: 0,
    bankName: '',
    bankAccount: ''
  }
]);

// 日期选择器的 change 事件处理函数
const handleDateChange = (val) => {
  if (val) {
    // 创建一个 Date 对象（如果 val 不是 Date 对象的话，需要先转换）
    const date = new Date(val);
    // 格式化日期为 YYYY-MM-DD 格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    projectInfo.value.outbounddate = `${year}-${month}-${day}`;//+' 00:00:00'
  } else {
    projectInfo.value.outbounddate = null;
  }
};

// 模拟项目信息数据
const projectInfo = ref({
  checkstatus:'',//存储审核状态
  status: '-1',//保存传-1，保存并通过传2"
  projectName: '',
  projectId: '',
  outFee: '',//外拨总金额
  isAuditor:'',//是否有审核权限
  availableAllocatedAmount: '',
  outbounddate: '',
  chargerName: '', //负责人名称
  isOutFee: '',//已拨经费
  outFeeIncheck: '',//外拨待审核金额
  projectOutboundList: [
    {
      index: '',
      unitName: '',//合作单位名称
      chargerName: '',//负责人
      isOutFee: '', //已外拨(万元)
      notOutFee: '',//未外拨
      outboundFee: '',//外拨经费(万元)
      bankName: '',//银行名
      bankNum: ''//卡号
    }
  ]
});
const JfwbDialogcompile = ref(false);

// 定义事件，用于通知父组件保存操作
const emits = defineEmits(['getlist','save','saveAndPass', 'close', 'getselectVproject']);

// 检查外拨经费是否不大于未外拨经费，并记录不符合项的合作单位名称
const checkOutboundFee = () => {
  const invalidUnitNames = [];
  for (const item of projectInfo.value.projectOutboundList) {
    const outboundFeeInYuan = (parseFloat(item.outboundFee) || 0) * 10000;
    const notOutFee = parseFloat(item.notOutFee) || 0;
    if (outboundFeeInYuan > notOutFee) {
      invalidUnitNames.push(item.unitName);
    }
  }
  if (invalidUnitNames.length > 0) {
    ElMessage({
      type: 'error',
      message: `存在外拨经费大于未外拨经费的情况，涉及合作单位：${invalidUnitNames.join(', ')}，请重新输入！`
    });
    return false;
  }
  return true;
};

// 提交按钮点击事件处理函数
const submit = () => {
  if (!checkOutboundFee()) {
    return;
  }
  projectInfo.value.status = '1';
  loading.value = true
  edit(convertOutboundFeeToYuan(projectInfo.value))
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            type:'success',
            message: res.msg
          });
          JfwbDialogcompile.value = false;
          emits('getlist');
        } else {
          ElMessage({
            type: 'info',
            message: res.msg
          });
        }
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
};

// 保存按钮点击事件处理函数
const handleSave = () => {
  if (!checkOutboundFee()) {
    return;
  }
  projectInfo.value.status = '-1';
  loading.value = true
  edit(convertOutboundFeeToYuan(projectInfo.value))
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            type:'success',
            message: res.msg
          });
          JfwbDialogcompile.value = false;
          emits('getlist');
        } else {
          ElMessage({
            type: 'info',
            message: res.msg
          });
        }
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
};

// 保存并通过按钮点击事件处理函数
const handleSaveAndPass = () => {
  if (!checkOutboundFee()) {
    return;
  }
  projectInfo.value.status = '2';
  loading.value = true
  edit(convertOutboundFeeToYuan(projectInfo.value))
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            type:'success',
            message: res.msg
          });
          JfwbDialogcompile.value = false;
          emits('getlist');
        } else {
          ElMessage({
            type: 'info',
            message: res.msg
          });
        }
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
};

// 处理外拨经费失去焦点事件
const handleOutboundFeeBlur = (row) => {
  const value = row.outboundFee;
  if (value!== undefined) {
    const parts = String(value).split('.');
    if (parts.length > 1 && parts[1].length > 6) {
      row.outboundFee = parseFloat(parts[0] + '.' + parts[1].slice(0, 6));
    } else {
      row.outboundFee = parseFloat(value);
    }
  }
};

// 定义一个方法用于打开弹窗
const opencompileDialog = (row) => {
  JfwbDialogcompile.value = true;
  getEditInfo({ Id: row.id })
      .then((res) => {
        if (res.data) {
          const mergedData = {...projectInfo.value ,...res.data,...row,};

         // projectInfo.value = mergedData;
          // projectInfo.value = res.data;
          // if(row.isAuditor){
          //   projectInfo.isAuditor = res.data.isAuditor;
          // }

          projectInfo.value = convertOutboundFeeToWanYuan(mergedData);
          console.log(mergedData)
          console.log(res.data )
          projectInfo.value.projectOutboundList.forEach(item => {
            item.outboundFee = parseFloat(item.outboundFee).toString();
          });
        }
      });
  projectInfo.value.checkstatus = row.checkstatus
};

// 暴露 openDialog 方法供父组件调用
defineExpose({
  opencompileDialog
});
</script>

<style scoped lang="scss">
.title-col {
  color: #337AB7;
  font-weight: bolder;
  margin: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>